package nina.yiyou.salary.input.util

import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.CellType
import org.apache.poi.ss.usermodel.DateUtil

import java.time.LocalDateTime

class CellValueGetter {

  CellValueGetter(Cell cell) {
    _cell = cell
  }

  Object get() {
    CellType cellType = getCellType(_cell)
    if (cellType == CellType.BLANK) {
      return null
    }
    if (cellType == CellType.BOOLEAN) {
      return _cell.booleanCellValue
    }

    if (cellType == CellType.NUMERIC) {
      if (DateUtil.isCellDateFormatted(_cell)) {
        def c = Calendar.getInstance()
        c.setTime(_cell.dateCellValue)
        return LocalDateTime.of(c.get(Calendar.YEAR), c.get(Calendar.MONTH) + 1, c.get(Calendar.DAY_OF_MONTH),
            c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), c.get(Calendar.SECOND))
      }
      return _cell.numericCellValue
    }

    try {
      return _cell.stringCellValue
    } catch (Exception e) {
      throw new UnsupportedOperationException(
          "${_cell.sheet.sheetName}[R${_cell.row.rowNum + 1}C${_cell.columnIndex + 1}]", e)
    }
  }

  private CellType getCellType(Cell cell) {
    if (cell == null) {
      return CellType.BLANK
    }
    if (cell.cellType == CellType.FORMULA) {
      return cell.getCachedFormulaResultType()
    }
    return cell.cellType
  }

  private final Cell _cell
}
